package com.tools.scanner.database

import androidx.room.Dao
import androidx.room.Database
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.Update
import com.tools.scanner.QrApp
import com.tools.scanner.bean.BarcodeSchema
import java.io.Serializable

@Database(
    entities = [PdfInfo::class, QrHistory::class],
    version = 1,
    exportSchema = false
)
abstract class AppDatabase : RoomDatabase() {
    abstract fun createDao(): ScannerDatabase
}

@Entity(tableName = "qr_info")
data class QrHistory(
    @PrimaryKey(autoGenerate = true) var id: Long = 0,
    val ctime: Long = System.currentTimeMillis(),
    var utime: Long = System.currentTimeMillis(),
    val schema: BarcodeSchema,
    var content: String,
    var formatContent: String,
    var photoPath: String,
    var isDelete: Int = 0,
    var isCreate: Int = 0
) : Serializable

@Entity(tableName = "pdf_info")
data class PdfInfo(
    @PrimaryKey(autoGenerate = true) var id: Long = 0,
    val ctime: Long = System.currentTimeMillis(),
    var utime: Long = System.currentTimeMillis(),
    var name: String,
    val firstPhoto: String,
    val photoPath: String,
    val num: Int,
    val pdfPath: String,
    var isDelete: Int = 0,
) : Serializable

@Dao
interface ScannerDatabase {
    companion object {
        private var INSTANCE: ScannerDatabase? = null
        fun get(): ScannerDatabase {
            if (INSTANCE == null) {
                INSTANCE =
                    Room.databaseBuilder(QrApp.app, AppDatabase::class.java, "scanner")
                        .build()
                        .createDao()
            }
            return INSTANCE!!
        }
    }

    @Insert
    suspend fun savePdfInfo(info: PdfInfo): Long

    @Query("SELECT * FROM pdf_info WHERE id = :id")
    fun queryPdfInfo(id: Int): PdfInfo?

    @Query(
        """
    SELECT * FROM pdf_info 
    WHERE isDelete = 0
    AND (:contentQuery = '' OR name LIKE :contentQuery)
    ORDER BY ctime DESC
"""
    )

    fun searchPdfInfo(contentQuery: String = ""): List<PdfInfo>

    @Update
    fun changePdfFileName(pdfInfo: PdfInfo)

    @Insert
    suspend fun saveQrHistory(history: QrHistory): Long

    @Query("SELECT * FROM qr_info WHERE id = :id AND isDelete = 0")
    fun queryQrHistory(id: Int): QrHistory?

    @Query(
        """
    SELECT * FROM qr_info 
    WHERE isDelete = 0 
    AND isCreate = :isCreate
    AND (:contentQuery = '' OR content LIKE :contentQuery)
    ORDER BY ctime DESC
"""
    )
    fun searchQrHistory(isCreate: Int, contentQuery: String = ""): List<QrHistory>
}